import axios from 'axios'
import {
	MessageBox,
	Message
} from 'element-ui'
import store from '@/store'

// create an axios instance
const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
	withCredentials: true, // send cookies when cross-domain requests
	timeout: 15000 // request timeout
})

// request interceptor
service.interceptors.request.use(
	config => {
		config.headers['Content-Type'] = 'application/json'

		// console.log(res.header['Cookie'])
		// sessionStorage.setItem('TOKEN',config.header['Set-Cookie'].split(';')[0])
		return config
	},
	error => {
		console.log(error) // for debug
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	response => {
		const res = response.data
		// if the custom code is not 20000, it is judged as an error.
		if (res.code !== 0) {
			if (res.msg) {
				Message({
					message: res.msg || 'error',
					type: 'error',
					duration: 5 * 1000
				})
			}
			// 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
			if (res.code === 1003) {
				// to re-login
				MessageBox.confirm('您的账号在另一个地点登录了,您已被迫下线。如果这不是您本人的操作,那么您的密码很可能已泄露。请及时修改', '提示', {
					confirmButtonText: '重新登录',
					type: 'warning',
					center: true,
					showClose: false,
					showCancelButton: false,
					closeOnPressEscape: false,
					closeOnClickModal: false
				}).then(() => {
					sessionStorage.clear()
					const _origin = window.location.origin
					const url = _origin + '/index.html#/login'
					window.open(url, '_self')
				})
			}
			if (res.code === 1001) {
				sessionStorage.clear()
				const _origin = window.location.origin
				const url = _origin + '/index.html#/login'
				window.open(url, '_self')
			}
			return Promise.reject(res.msg || 'error')
		} else {
			return res
		}
	},
	error => {
		const reg = new RegExp(/504|503|500|400|404/)
		if (reg.test(error.message) || error.message === 'Network Error') {
			Message({
				message: '网络断了，请检查网络！',
				type: 'error',
				duration: 5 * 1000
			})
		} else {
			Message({
				message: error.message,
				type: 'error',
				duration: 5 * 1000
			})
			return Promise.reject(error)
		}
	}
)

export default service
